import { ref } from 'vue'
import app from '@/app'
import { create } from '@/api/erp/outbound'
import { countLimit } from '@/api/store/goods'
import outboundStore from '../../../store/outbound'

const store = {
  data: ref({}),
  goods: ref([]),
  callback: null,

  getData() {
    return this.data.value
  },

  getGoods() {
    return this.goods.value
  },

  init(data, callback = null) {
    this.data.value = Object.assign({
      client_id    : 0,
      client_name  : '',
      client_data  : {},
      code         : app.time.code(),
      name         : '',
      count        : 0,
      goods        : []
    }, data)

    this.goods.value = data ? data.goods : []
    this.callback = callback
    this.update()
  },

  // 载入客户
  client(data) {
    this.getData().client_data = data ?? {}
    this.getData().client_id = data ? data.id : 0
    this.getData().client_name = data ? data.name : ''
  },

  // 更新统计
  update() {
    let count = 0

    // 循环商品
    this.getGoods().forEach(item => {
      // 数量统计
      count += item.count
    })

    // 总数量
    this.getData().count = count

    console.log(this.getData())
  },

  // 新增栏
  async add(goods) {
    this.getGoods().push({
      id          : this.getGoods().length,
      goods_id    : goods.id,
      goods_number: goods.number,
      goods_name  : goods.name,
      goods_code  : goods.code,
      goods_image : goods.image,
      unit        : goods.unit,
      unit_count  : goods.unit_count,
      count       : 1,
    })
    this.update()
  },

  // 删除
  del(index) {
    this.getGoods().splice(index, 1)
    this.update()
  },

  // 提交
  post() {
    // 整理数据
    this.getData().goods = this.getGoods()
    return new Promise((resolve, jeject) => {
      create(this.getData()).then(res => {
        this.over()
        resolve(res)
      }).catch(res => {
        jeject(res)
      })
    })
  },

  // 提交完成
  over() {
    // 列表加载第一页
    outboundStore.reset(1)
    // 更改库存
    countLimit(this.getGoods(), true, false)
    // 执行回调
    if(this.callback) {
      this.callback()
    }
    // 重置数据
    this.init()
  } 
}

// 首次执行
store.init()

export default store